package com.mes.cloud.intercept;

import com.mes.cloud.aop.AopContext;
import com.mes.cloud.dto.QuartzTaskDTO;
import com.mes.cloud.quartz.QuartzPlugin;
import com.mes.cloud.service.QuartzTaskService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @author: wxm
 * @date: 2019/6/11 10:13
 * @version: 1.0
 */
public class TaskIntercept extends MetaObjectIntercept{

    @Autowired
    private QuartzTaskService quartzTaskService ;

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public String addAfter(AopContext ac) throws Exception {
        String className = ac.record.getStr("clazz");
        String exp = ac.record.getStr("exp");

        Class clazz = Class.forName(className);
        JobDetail job = JobBuilder.newJob(clazz).withIdentity(className, className).build();
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(className, className).withSchedule(CronScheduleBuilder.cronSchedule(exp)).build();

        // 新增任务
        QuartzPlugin.scheduler.scheduleJob(job, trigger);
        // 默认暂停
        QuartzPlugin.scheduler.pauseJob(job.getKey());

        return null;
    }

    @Override
    public String deleteAfter(AopContext ac) throws Exception {
        String className = ac.record.getStr("clazz");

        // 删除任务(自动删除关联触发器)
        JobKey jobKey = JobKey.jobKey(className, className);

        QuartzPlugin.scheduler.deleteJob(jobKey);

        return null;
    }

    @Override
    public String updateAfter(AopContext ac) throws Exception {
        String className = ac.record.getStr("clazz");
        String exp = ac.record.getStr("exp");

        // 表达式调度构建器
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(exp);

        // 重新构建触发器覆盖原触发器
        TriggerKey triggerKey = TriggerKey.triggerKey(className, className);
        CronTrigger trigger = (CronTrigger) QuartzPlugin.scheduler.getTrigger(triggerKey);
        trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

        // 重置任务
        QuartzPlugin.scheduler.rescheduleJob(triggerKey, trigger);

        // 暂停
        QuartzPlugin.scheduler.pauseTrigger(triggerKey);

        // 状态变更为暂停
        quartzTaskService.updateQuartzTaskState(Integer.valueOf(ac.record.getStr("id")), QuartzTaskDTO.STATE_STOP);

        return null;
    }

    @Override
    public String addBefore(AopContext ac) throws Exception {
        String cs = ac.record.getStr("clazz");
        Map<Object, Object> condition = new HashMap<>();
        condition.put("clazz",cs);
        List<QuartzTaskDTO> list = quartzTaskService.getQuartzTaskList(condition);
        if(list.size() > 0){
            throw new Exception("Job实现类已经存在:" + cs);
        }
        return null;
    }


}
